<template>
  <van-popup v-model:show="show" class="p-4" round>
    <div class="text-center font-bold mb-2">修改登录密码</div>
    <div class="">
      <div class="mb-4">
        <label for="password">当前密码：</label>
        <input type="text" v-model="formRef.oldPassword" class="border rounded p-1" />
      </div>

      <div class="mb-4">
        <label for="password">新的密码：</label>
        <input type="text" v-model="formRef.newPassword" class="border rounded p-1" />
      </div>

      <div class="mb-4">
        <label for="password">确认密码：</label>
        <input type="text" v-model="formRef.confirmPassword" class="border rounded p-1" />
      </div>
    </div>
    <div class="m-2 flex justify-between">
      <button
        @click="show = false"
        class="border border-white rounded text-black bg-gray-100 px-4 py-1"
      >
        返回
      </button>
      <button @click="submit" class="border border-white rounded text-white bg-blue-500 px-4 py-1">
        保存
      </button>
    </div>
  </van-popup>
</template>

<script setup lang="ts">
import { computed, defineEmits, ref } from 'vue'
import { changePasswordApi } from '@/apis/user'
import { showToast } from 'vant'

const emit = defineEmits(['update:show-modal'])
const formRef = ref({
  newPassword: '',
  oldPassword: '',
  confirmPassword: ''
})

const props = defineProps({
  showModal: {
    type: Boolean,
    default: false
  }
})

const show = computed({
  get() {
    return props.showModal || false
  },
  set(val) {
    emit('update:show-modal', val)
  }
})

function submit() {
  if (formRef.value.newPassword === formRef.value.confirmPassword) {
    changePasswordApi({
      oldPassword: formRef.value.oldPassword,
      newPassword: formRef.value.newPassword
    }).then(() => {
      showToast({
        message: '修改成功',
        duration: 1000,
        onClose: () => {
          show.value = false
        }
      })
    })
  } else {
    showToast({
      message: '两次密码不一致',
      duration: 1000
    })
  }
}
</script>
